package com.henry.imkit.request

import com.henry.imkit.BuildConfig
import com.henry.imkit.IMKit
import com.henry.imkit.network.*
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.util.concurrent.TimeUnit

object IMRetrofit {

    private var retrofit: Retrofit? = null

    var service: IMApiService = getApi()

    private fun getApi(): IMApiService {
        return getRetrofit()!!.create(IMApiService::class.java)
    }

    private fun getRetrofit(): Retrofit? {
        if (retrofit == null) {
            if (IMKit.instance.domain.isNotEmpty()) {
                retrofit = Retrofit.Builder()
                        .baseUrl(IMKit.instance.domain)  // baseUrl
                        .client(getOkHttpClient())
                        .addConverterFactory(FastJsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
            }
        }
        return retrofit
    }

    fun onDestroy() {
        retrofit = null
    }

    fun updateService(baseUrl: String) {
        if (baseUrl.isNotEmpty()) {
            retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)  // baseUrl
                .client(getOkHttpClient())
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
            service = retrofit!!.create(IMApiService::class.java)
        }
    }

    /**
     * 获取 OkHttpClient
     */
    fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient().newBuilder()
        val httpLoggingInterceptor = HttpLoggingInterceptor()

        if (BuildConfig.DEBUG) {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }

        builder.run {
            addInterceptor(IMQueryParameterInterceptor())
            addInterceptor(HeaderInterceptor())
            addInterceptor(httpLoggingInterceptor)
            connectTimeout(15, TimeUnit.SECONDS)
            readTimeout(15, TimeUnit.SECONDS)
            writeTimeout(15, TimeUnit.SECONDS)
            retryOnConnectionFailure(true) // 错误重连
            // cookieJar(CookieManager())
            SSLSocketFactoryUtils.getSSLSocket()?.let { SSLSocketFactoryUtils.getX509TrustManager()?.let { it1 -> sslSocketFactory(it, it1) } }
            SSLSocketFactoryUtils.getHostnameVerifier()?.let { hostnameVerifier(it) }
        }
        return builder.build()
    }

}